# This script will read in AWAP data, having already been extracted from Raw format by Lukes script
# It will then resize the files and change them to the appropriate datum.

# Establish directories

in.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/LinkeTurbidityWorldExtent/'
setwd(in.dir)
out.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/LinkeTurbidityFinal/'

# Load libraries
necessary=c('SDMTools')
#check if library is installed
installed = necessary %in% installed.packages()
#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)
#load the libraries
for (lib in necessary) library(lib,character.only=T)

# Read in base ASCII file that is datum WGS1984-UTM, 250 m res, and sized to WTplusbigbuffer

base.asc = read.asc('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/bigbuffer/dem250bigbuffer.asc')

# Establish row/column positions for 250 m grid


base.pos = as.data.frame(which(is.finite(base.asc), arr.ind = T)) 

# Add east and north to this data frame of row/column positions

base.pos$lat = getXYcoords(base.asc)$x[base.pos$row]
base.pos$long = getXYcoords(base.asc)$y[base.pos$col]

#Get a list of all files located in in.dir

lt.list = list.files(in.dir, pattern='.asc')

# Loop through all files in in.dir and resample them

for (map in lt.list)

	{

	# Read in the first map to check it's size and res

	t.asc = read.asc(paste(in.dir,map,sep=''))

	# Extract AWAP data and store against positions from base.pos
	
	t.pos = data.frame(base.pos$col, base.pos$row, extract.data(cbind(base.pos$lat,base.pos$long),t.asc))

	# Write AWAP data back into base.asc, export as an ASCII

	base.asc[cbind(base.pos$row,base.pos$col)]=t.pos[,3]

	write.asc(x=base.asc, file=paste(out.dir,map,sep=""))
	
	cat(map)
	
	}
	
# End